<template>
  <div class="room-status-container">
    <div class="header">
      <h2>会议室状态</h2>
      <div class="header-actions">
        <el-button type="primary" size="small" @click="fetchRooms" class="refresh-button">
          <el-icon><Refresh /></el-icon>刷新状态
        </el-button>
      </div>
    </div>
    <div class="card-container">
      <el-card v-for="room in rooms" :key="room.id" class="room-card" :class="{'room-card-used': room.status === '使用中', 'room-card-idle': room.status === '空闲', 'room-card-maintenance': room.status === '维护中', 'room-card-locked': room.status === '锁定中'}">
        <div class="card-header">
          <div class="room-info">
            <h3>{{ room.name }}</h3>
            <el-tag :type="getStatusType(room.status)" effect="dark" class="status-tag">{{ room.status }}</el-tag>
          </div>
          <div class="room-icon">
            <el-icon v-if="room.status === '空闲'"><SuccessFilled /></el-icon>
            <el-icon v-else-if="room.status === '使用中'"><Timer /></el-icon>
            <el-icon v-else-if="room.status === '维护中'"><Tools /></el-icon>
            <el-icon v-else-if="room.status === '锁定中'"><Lock /></el-icon>
          </div>
        </div>
        <div class="card-content">
          <div v-if="room.status === '使用中'" class="time-info">
            <div class="time-item">
              <el-icon><Calendar /></el-icon>
              <span><strong>开始时间:</strong> {{ formatTime(room.startHour) }}</span>
            </div>
            <div class="time-item">
              <el-icon><AlarmClock /></el-icon>
              <span><strong>结束时间:</strong> {{ formatTime(room.endHour) }}</span>
            </div>
            <el-progress 
              :percentage="calculateTimePercentage(room.startHour, room.endHour)" 
              :status="isEndTimePassed(room.endHour) ? 'success' : 'exception'" 
              class="time-progress"
            />
          </div>
          <div v-if="room.status === '锁定中'" class="controls locked-controls">
            <el-icon><Lock /></el-icon>
            <el-tag type="danger" effect="dark">不可更改</el-tag>
          </div>
          <div v-else-if="room.status === '空闲' || room.status === '维护中' || (room.status === '使用中' && isEndTimePassed(room.endHour))" class="controls">
            <el-button type="primary" size="small" @click="openStatusDialog(room)" class="action-button">
              <el-icon><Edit /></el-icon>修改状态
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 状态修改对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`修改${selectedRoom?.name || '会议室'}状态`"
      width="500px"
      class="status-dialog"
      destroy-on-close
    >
      <div class="dialog-content">
        <div class="room-status-form">
          <div class="form-icon">
            <el-icon v-if="statusForm.status === '空闲'"><SuccessFilled /></el-icon>
            <el-icon v-else-if="statusForm.status === '维护中'"><Tools /></el-icon>
            <el-icon v-else><Edit /></el-icon>
          </div>
          <div class="form-item">
            <label>会议室状态：</label>
            <el-select v-model="statusForm.status" placeholder="请选择状态" class="status-select">
              <el-option v-for="option in availableStatusOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-button">
            <el-icon><Close /></el-icon>取消
          </el-button>
          <el-button type="primary" @click="submitStatusChange" class="confirm-button">
            <el-icon><Check /></el-icon>确认修改
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoomStore } from '../stores/RoomStore'
import {
  Refresh,
  SuccessFilled,
  Timer,
  Tools,
  Lock,
  Calendar,
  AlarmClock,
  Edit,
  Close,
  Check
} from '@element-plus/icons-vue'

const roomStore = useRoomStore()
const rooms = ref([])

// 对话框相关
const dialogVisible = ref(false)
const selectedRoom = ref(null)
const statusForm = reactive({
  status: ''
})
const availableStatusOptions = ref([])

// 表单验证规则
const statusRules = {
  status: [
    { required: true, message: '请选择会议室状态', trigger: 'change' }
  ]
}

// 计算会议室使用时间百分比
const calculateTimePercentage = (startHour, endHour) => {
  if (!startHour || !endHour) return 0
  
  const today = new Date().toISOString().split('T')[0]
  const startTime = new Date(`${today}T${startHour}`).getTime()
  const endTime = new Date(`${today}T${endHour}`).getTime()
  const now = new Date().getTime()
  
  if (now < startTime) return 0
  if (now > endTime) return 100
  
  const totalDuration = endTime - startTime
  const elapsedDuration = now - startTime
  return Math.round((elapsedDuration / totalDuration) * 100)
}

// 获取会议室数据
const fetchRooms = async () => {
 await roomStore.fetchRooms()
 rooms.value = roomStore.rooms
}

// 组件挂载时获取数据
onMounted(async () => {
  await fetchRooms()
})

const getStatusType = (status) => {
  switch (status) {
    case '空闲':
      return 'success'
    case '使用中':
      return 'danger'
    case '维护中':
      return 'warning'
    case '锁定中':
      return 'info'
    default:
      return 'info'
  }
}

const formatTime = (time) => {
  if (!time) return '未设置'
  // 获取当前日期，格式为 YYYY-MM-DD
  const today = new Date().toISOString().split('T')[0]
  // 拼接当前日期和时间字符串，生成完整的日期时间
  const dateTime = new Date(`${today}T${time}`)
  if (isNaN(dateTime.getTime())) return '未设置'
  return dateTime.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const isEndTimePassed = (endHour) => {
  if (!endHour) return false
  // 获取当前日期，格式为 YYYY-MM-DD
  const today = new Date().toISOString().split('T')[0]
  // 拼接当前日期和时间字符串，生成完整的日期时间
  const endTime = new Date(`${today}T${endHour}`)
  const now = new Date()
  return endTime < now
}

const convertStatusToEnglish = (status) => {
  switch (status) {
    case '空闲':
      return 'idle'
    case '维护中':
      return 'maintenance'
    case '使用中':
      return 'in_used'
    case '锁定中':
      return 'locked'
    default:
      return status
  }
}

// 打开状态修改对话框
const openStatusDialog = (room) => {
  selectedRoom.value = room
  statusForm.status = room.status

  // 根据当前状态生成可选项
  if (room.status === '空闲') {
    availableStatusOptions.value = [{ label: '维护中', value: '维护中' }]
  } else if (room.status === '维护中') {
    availableStatusOptions.value = [{ label: '空闲', value: '空闲' }]
  } else if (room.status === '使用中' && isEndTimePassed(room.endHour)) {
    availableStatusOptions.value = [
      { label: '空闲', value: '空闲' },
      { label: '维护中', value: '维护中' }
    ]
  }

  dialogVisible.value = true
}

// 提交状态修改
const submitStatusChange = async () => {
  if (!selectedRoom.value) return

  const success = await roomStore.updateRoomStatus(selectedRoom.value.id, statusForm.status)
  
  if (success) {
    await fetchRooms()
    selectedRoom.value.status = statusForm.status
    ElMessage({
      type: 'success',
      message: '状态修改成功！'
    })
    dialogVisible.value = false
  }
}
</script>

<style scoped>
.room-status-container {
  padding: 0 0px 24px 24px;
  margin: auto 0px 0px 10px;
  min-height: 100vh;
  background-color: #f5f7fa;
  background-image: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  overflow-x: hidden; /* 防止横向滚动 */
  width: 100%;
  box-sizing: border-box;
}

.header {
  background: white;
  padding: 24px;
  border-radius: 0 0 16px 16px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 32px;
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header h2 {
  margin: 0;
  color: #1a237e;
  font-size: 28px;
  font-weight: 600;
  background: linear-gradient(90deg, #1a237e 0%, #3949ab 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.refresh-button {
  background: linear-gradient(90deg, #3949ab 0%, #5c6bc0 100%);
  border: none;
  padding: 8px 16px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.refresh-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(57, 73, 171, 0.3);
}

.card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 32px;
  padding: 0 12px;
  max-width: 1600px;
  margin: 0 auto;
}

.room-card {
  background: white;
  border-radius: 20px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  border: none;
}

.room-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
}

.room-card-idle {
  border-top: 5px solid #67c23a;
}

.room-card-used {
  border-top: 5px solid #f56c6c;
}

.room-card-maintenance {
  border-top: 5px solid #e6a23c;
}

.room-card-locked {
  border-top: 5px solid #909399;
}

.card-header {
  padding: 24px;
  background: linear-gradient(135deg, #f8faff 0%, #f0f4fa 100%);
  border-bottom: 1px solid #eef2f7;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.room-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.card-header h3 {
  margin: 0;
  color: #1a237e;
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.room-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #3949ab 0%, #5c6bc0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  box-shadow: 0 4px 12px rgba(57, 73, 171, 0.3);
}

.status-tag {
  border-radius: 50px;
  padding: 6px 16px;
  font-weight: 500;
  font-size: 14px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: inline-flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
}

.card-content {
  padding: 24px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.time-info {
  margin: 16px 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.time-item {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #546e7a;
  font-size: 15px;
}

.time-item .el-icon {
  color: #3949ab;
  font-size: 18px;
}

.time-item strong {
  color: #1a237e;
  font-weight: 500;
  min-width: 80px;
}

.time-progress {
  margin-top: 12px;
}

.controls {
  display: flex;
  justify-content: center;
  margin-top: 24px;
}

.locked-controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  color: #f56c6c;
}

.locked-controls .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.action-button {
  background: linear-gradient(90deg, #3949ab 0%, #5c6bc0 100%);
  border: none;
  padding: 10px 24px;
  border-radius: 50px;
  font-weight: 500;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(57, 73, 171, 0.2);
  display: flex;
  align-items: center;
  gap: 8px;
}

.action-button:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 16px rgba(57, 73, 171, 0.3);
}

/* 对话框样式 */
.status-dialog :deep(.el-dialog) {
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.15);
}

.status-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #f8faff 0%, #f0f4fa 100%);
  padding: 24px 30px;
  margin: 0;
  border-bottom: 1px solid #eef2f7;
}

.status-dialog :deep(.el-dialog__title) {
  color: #1a237e;
  font-size: 20px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.status-dialog :deep(.el-dialog__body) {
  padding: 30px;
}

.status-dialog :deep(.el-dialog__footer) {
  padding: 20px 30px;
  border-top: 1px solid #eef2f7;
  display: flex;
  justify-content: flex-end;
  gap: 16px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.room-status-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
}

.form-icon {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  background: linear-gradient(135deg, #3949ab 0%, #5c6bc0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 28px;
  box-shadow: 0 8px 16px rgba(57, 73, 171, 0.2);
  margin-bottom: 8px;
}

.form-item {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.form-item label {
  font-size: 16px;
  font-weight: 500;
  color: #1a237e;
}

.status-select {
  width: 100%;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 4px 12px;
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(57, 73, 171, 0.2);
}

.cancel-button {
  border-radius: 50px;
  padding: 10px 24px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.confirm-button {
  background: linear-gradient(90deg, #3949ab 0%, #5c6bc0 100%);
  border: none;
  border-radius: 50px;
  padding: 10px 24px;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(57, 73, 171, 0.2);
}

.confirm-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(57, 73, 171, 0.3);
}

@media (max-width: 1600px) {
  .card-container {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}

@media (max-width: 1200px) {
  .card-container {
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  }
  
  .header h2 {
    font-size: 24px;
  }
}

@media (max-width: 992px) {
  .card-container {
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 24px;
  }
}

@media (max-width: 768px) {
  .room-status-container {
    padding: 0 16px 16px 16px;
  }

  .header {
    padding: 16px 20px;
    margin-bottom: 20px;
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
  }
  
  .refresh-button {
    width: 100%;
  }

  .card-container {
    grid-template-columns: 1fr;
    gap: 20px;
    padding: 0;
  }

  .card-header {
    padding: 20px;
  }

  .card-content {
    padding: 20px;
  }
  
  .room-card:hover {
    transform: translateY(-5px);
  }
  
  .status-dialog :deep(.el-dialog) {
    width: 90% !important;
    margin: 0 auto;
  }
  
  .status-dialog :deep(.el-dialog__body) {
    padding: 20px;
  }
  
  .status-dialog :deep(.el-dialog__footer) {
    padding: 16px 20px;
    flex-direction: column;
    gap: 10px;
  }
  
  .dialog-footer .el-button {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .room-status-container {
    padding: 0 12px 12px 12px;
    width: 100%;
    overflow-x: hidden;
  }
  
  .header {
    padding: 16px;
    margin-bottom: 16px;
    width: 100%;
    box-sizing: border-box;
  }
  
  .card-header {
    padding: 16px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    width: 100%;
    box-sizing: border-box;
  }
  
  .room-icon {
    position: absolute;
    top: 16px;
    right: 16px;
    width: 36px;
    height: 36px;
    font-size: 18px;
  }
  
  .room-info {
    width: 100%;
  }
  
  .card-content {
    padding: 16px;
    width: 100%;
    box-sizing: border-box;
  }
  
  .time-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
    width: 100%;
    box-sizing: border-box;
  }
  
  .time-item .el-icon {
    margin-bottom: 4px;
  }
  
  .card-container {
    width: 100%;
    box-sizing: border-box;
    padding: 0;
  }
}
</style>